package com.kfm.shop.system.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.kfm.shop.common.ex.ServiceException;
import com.kfm.shop.system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的 token
        String header = request.getHeader("Authorization");

        if (StringUtils.hasText(header)) {
            // 验证 token 是否有效
            try {
                JwtUtil.verify(header);
            } catch (TokenExpiredException e){
                throw new ServiceException("登录已过期，请重新登录");
            } catch (Exception e) {
                throw new ServiceException("token 无效，请重新登录");
            }
            return true;
        }

        throw new ServiceException("请先登录");
    }
}

